package com.cn.main.web;

import java.io.*;
import java.util.ArrayList;
import java.util.List;

/**
 * @author: chenyuncong
 * @Date: 2020/1/7 15:20
 */
public class FfmPegUtil {
    /**
     * 根据水印文字---添加视频水印
     * @param srcPath  原视频路径
     * @param tarVideoPath  生成后的视频路径
     * @param txt String  文字
     * @param fontSize   每个字的宽度和高度是一样的
     *  ffmpeg -i /root/test.mp4 -vf "drawtext=fontsize=35:fontcolor=white:fontfile=simhei.ttf:text='粤ADE5028':x=474:y=25" -y 3.avi
     * @return
     */
    public static boolean processFfmpegWatermkByFont(String srcPath, String tarVideoPath,  String txt, int fontSize) {
        if(!checkfile(srcPath)){
            return false;
        }
        List<String> commend = new ArrayList<String>();
        commend.add("ffmpeg");
        commend.add("-i");
        commend.add(srcPath); //需要校验文件是否存在
        commend.add("-vf");
        commend.add(getParamPosition(txt,fontSize,null));
        commend.add("-y");
        commend.add(tarVideoPath);
        StringBuffer test=new StringBuffer();
        for(int i=0;i<commend.size();i++)
            test.append(commend.get(i)+" ");
        System.out.println(test);
        try {
            Runtime rt = Runtime.getRuntime();
            Process proc = rt.exec(test.toString());
            InputStream stderr = proc.getErrorStream();
            InputStreamReader isr = new InputStreamReader(stderr);
            BufferedReader br = new BufferedReader(isr);
            String line = null;
            while ( (line = br.readLine()) != null);

        } catch (IOException e) {
            e.printStackTrace();
        }
        System.out.println("视频转换成功");
        return false;
    }

    /**
     * 校验文件是否存在
     * @param path
     * @return
     */
    private static boolean checkfile(String path) {
        File file = new File(path);
        if (file.isFile()) {
            return true;
        }
        return false;
    }
    // drawtext=fontsize=35:fontcolor=white:fontfile=simhei.ttf:text='粤ADE5028':x=474:y=25"
    private static String getParamPosition(String txt, int fontSize, String fontColor){
        StringBuffer sb = new StringBuffer();
        sb.append("drawtext=fontsize=").append(fontSize).append(":");
        sb.append("fontcolor=").append(fontColor==null?"white":fontColor).append(":");
        sb.append("fontfile=simhei.ttf").append(":");
        sb.append("text=").append("'").append(txt).append("':");
        sb.append("x=474:y=25");
        return sb.toString();
    }

}
